function addPageClickEvent(button, pageNum) {
    button.addEventListener('click', async () => {
        if (pageNum >= 1 && pageNum <= window.totalPages) {
            currentPage = pageNum;
            let baseUrl = Alpine.$data(document.querySelector('[x-data]')).selectedOption
            let { data, total } = await invoke('get_data_by_time_range', {
                after: window.endTime,
                before: window.startTime,
                page: pageNum,
                name: baseUrl
            });
            let totalPages = Math.ceil(total / 20);
            window.totalPages = totalPages;
            renderPagination(totalPages, currentPage);
            const columns = Object.keys(data[0]);

            data = data.map((item) => {
                return Object.values(item);
            })

            const columnWidths = calculateColumnWidths(data, columns);
            Alpine.$data(document.querySelector('[x-data]')).currentPage = "data";
            grid.updateConfig({
                columns: columnWidths,
                data: data,
            }).forceRender(document.getElementById("wrapper"));
        }
    });
}

const calculateColumnWidths = (data, columns) => {
    const colWidths = [];
    const tempElement = document.createElement("div");
    tempElement.style.position = "absolute";
    tempElement.style.visibility = "hidden";
    tempElement.style.whiteSpace = "nowrap";
    tempElement.style.fontSize = "14px"; // 与表格字体大小一致
    tempElement.style.padding = "10px"; // 与表格单元格内边距一致
    tempElement.style.border = "1px solid #ddd"; // 与表格边框一致
    document.body.appendChild(tempElement);

    // 遍历每一列
    for (let col = 0; col < data[0].length; col++) {
        let maxWidth = 0;

        // 遍历每一行
        data.forEach((row) => {
            tempElement.innerText = row[col];
            const width = tempElement.offsetWidth;
            if (width > maxWidth) {
                maxWidth = width;
            }
        });

        // 设置最小列宽
        colWidths.push({
            name: columns[col],
            width: `${Math.max(maxWidth, 130)}px`
        });
    }

    document.body.removeChild(tempElement);
    return colWidths;
};

function renderPagination(totalPages, currentPage) {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';

    const prevButton = document.createElement('button');
    prevButton.className = 'pagination-item';
    prevButton.textContent = '<';
    prevButton.disabled = currentPage === 1;
    addPageClickEvent(prevButton, currentPage - 1); // 绑定事件
    pagination.appendChild(prevButton);

    const pages = [];
    if (totalPages <= 7) {
        // 如果总页码数少于等于7，直接显示所有页码
        for (let i = 1; i <= totalPages; i++) {
            pages.push(i);
        }
    } else {
        // 确保“上一页”和“下一页”按钮始终在同一水平线
        // 显示当前页及其前后各2个页码
        for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
            pages.push(i);
        }

        // 显示第一页和最后一页
        if (!pages.includes(1)) {
            pages.unshift(1);
            if (pages[1] !== 2) {
                pages.splice(1, 0, '...');
            }
        }

        if (!pages.includes(totalPages)) {
            pages.push(totalPages);
            if (pages[pages.length - 2] !== totalPages - 1) {
                pages.splice(pages.length - 1, 0, '...');
            }
        }
    }

    pages.forEach(page => {
        if (page === '...') {
            const span = document.createElement('span');
            span.className = 'pagination-item';
            span.textContent = '...';
            pagination.appendChild(span);
        } else {
            const button = document.createElement('button');
            button.className = `pagination-item ${currentPage === page ? 'active' : ''}`;
            button.textContent = page;
            addPageClickEvent(button, page); // 绑定事件
            pagination.appendChild(button);
        }
    });

    const nextButton = document.createElement('button');
    nextButton.className = 'pagination-item';
    nextButton.textContent = '>';
    nextButton.disabled = currentPage === totalPages;
    addPageClickEvent(nextButton, currentPage + 1); // 绑定事件
    pagination.appendChild(nextButton);
}

